package com.sixmac.controller;

import com.alibaba.fastjson.JSONObject;
import com.sixmac.util.WeChatConfig;
import com.sixmac.common.base.BaseController;
import com.sixmac.common.constant.TempConstant;
import com.sixmac.core.plugins.dao.Blade;
import com.sixmac.core.toolbox.ajax.AjaxResult;
import com.sixmac.core.toolbox.kit.JsonKit;
import com.sixmac.module.*;
import com.sixmac.utils.HttpRequestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

/**
 * Created by admin on 2018/8/31.
 */

@Controller
@ResponseBody
@RequestMapping("/test")
public class TestController  extends BaseController {

    @Autowired
    WeChatConfig weChatConfig;

    @RequestMapping("/")
    public void t() {
        System.out.print("hello world");
    }


    @RequestMapping("/send")
    public AjaxResult send(Integer tenantId) {

        Tenant tenant = Blade.create(Tenant.class).findById(tenantId);

        if (tenant == null){
            return error("租客不存在");
        }

        AccessToken accessToken = Blade.create(AccessToken.class).findFirstBy("",null);
        if (accessToken!=null&&(System.currentTimeMillis() - accessToken.getCreatTime().getTime()) / (1000 * 60)>=60){
            Blade.create(AccessToken.class).delete(accessToken.getId());
            accessToken = null;
        }
        if (accessToken == null){
            String wxspAppid = weChatConfig.getAppId();
            String wxspSecret = weChatConfig.getSecret();
            String sr = HttpRequestUtil.sendGet("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxspAppid+"&secret="+wxspSecret, null);
            JSONObject json = JsonKit.parse(sr);
            //获取会话密钥（session_key）
            //  String session_key = json.get("session_key").toString();
            //用户的唯一标识（openid）
            if (json.containsKey("access_token")){
                String access_token = (String) json.get("access_token");
                accessToken = new AccessToken();
                accessToken.setCreatTime(new Date());
                accessToken.setToken(access_token);
                Blade.create(AccessToken.class).save(accessToken);
            }
        }

        TenantRoom tenantRoom = Blade.create(TenantRoom.class).findFirstBy(" tenantId="+tenant.getId()+" and approve=3 ",null);
        Landlord landlord = Blade.create(Landlord.class).findById(tenantRoom.getLandlordId());

        Room room = Blade.create(Room.class).findById(tenantRoom.getRoomId());

        AccessFrom form = Blade.create(AccessFrom.class).findFirstBy("isUse = 0",null);
        if(form != null){
            JSONObject object = new JSONObject();
            object.put("touser",tenant.getWechatKey());
            object.put("template_id", TempConstant.CHECK_TEMP_YES);
            object.put("page","/index/index");
            object.put("form_id",form.getFormId());
            JSONObject data = new JSONObject();
            JSONObject keyword1 = new JSONObject();
            keyword1.put("value","您的入住申请，已经审核成功，您可以去开锁了");
            JSONObject keyword3 = new JSONObject();
            keyword3.put("value",landlord.getName());
            JSONObject keyword4 = new JSONObject();
            keyword4.put("value",landlord.getMobile());
            data.put("keyword1",keyword1);
            data.put("keyword2",keyword3);
            data.put("keyword3",keyword4);
            object.put("data",data);

            String result = HttpRequestUtil.sendPost(" https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token="+accessToken.getToken(),object.toJSONString());
            System.out.println(result);

            //发送短信

            form.setIsUse(1);
            Blade.create(AccessFrom.class).update(form);
        }
        tenantRoom.setStatus(1);
        tenantRoom.setApprove(1);
        Blade.create(TenantRoom.class).update(tenantRoom);

        return success("成功");
    }
}
